package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全功能，关键字联想功能，使用es
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        try {
            // 1.校验参数
            if (dto == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            // 2.创建search请求对象
            SearchRequest searchRequest = new SearchRequest("app_info_article");
            // 3.设置查询条件
            searchRequest.source().size(0).suggest(
                    new SuggestBuilder().addSuggestion(
                            "keyWordSuggest",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .skipDuplicates(true)
                                    .prefix(dto.getSearchWords())
                                    .size(10)
                    )
            );
            // 4.发送请求，接收响应
            List<String> resultList = new ArrayList<>();
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            // 5.处理响应，封装结果
            Suggest suggest = response.getSuggest();
            if (suggest != null && suggest.size() > 0) {
                CompletionSuggestion keyWordSuggest = suggest.getSuggestion("keyWordSuggest");
                List<CompletionSuggestion.Entry.Option> options = keyWordSuggest.getOptions();
                if (options != null && options.size() > 0) {
                    for (CompletionSuggestion.Entry.Option option : options) {
                        resultList.add(option.getText().toString());
                    }
                }
            }
            // 6.返回结果
            return ResponseResult.okResult(resultList);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
